#-------------------------------------------------------------------------------
# Copyright (c) 2012 Huseyin BIYIK.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/gpl.html
# 
# Contributors:
#     Huseyin BIYIK - initial API and implementation
#-------------------------------------------------------------------------------

#TODO LIST:

# 1. statically  define header & payload lengths do not use ascii , use binary encoded data instead


debug = 0
from defs import *
import binascii, time
from call import call

class messages():
	## todo : make it strict when job is done
	## todo : consider encryption
	def __init__(self):
		self.types = ('connectrequest', 'connectaccept', 'connectdecline', 'disconnect', 'data', "bandwidthreport")
		self.dtypes = ('audio', 'video', 'bandwidth', 'text')

	def to_str(self, mtype, cll, typ=None):
		if str(type in self.types):
			msg = str(self.types[mtype]) + "\n"
			msg += str(cll.id) + "\n" 
			msg += str(cll.fromaddr) + "\n" 
			msg += str(cll.fromport) + "\n" 
			msg += str(cll.toaddr) + "\n" 
			msg += str(cll.toport) + "\n" 
			if not typ is None :
				msg += typ.name + "\n"
				msg += str(typ.timestamp) + "\n"
				msg += typ.payload + "\n"
			return msg
		else:	
			if debug > 0 : print str(msg) + " is not implemented accepted messages are: " + str(self.types)
			return None

	def from_str(self, str, cm):
		margs = str.split('\n')
		if len(margs) > 0 and margs[0] in self.types :
			mtype = margs[0]
			margs.pop(0)
			for i in range(len(self.types)):
				if mtype == self.types[i]:
					break
			mtype = i
			if cm.is_call(margs[0]) :
			##consider some security checks here
				cll = cm.calls[margs[0]]
			else:
				cll = call(margs[0], margs[3], int(margs[4]), margs[1], int(margs[2]))
			if len(margs) >= 7:
				cll.stream.set_type(margs[5],"enabled",mtype!=2)
				cll.stream.set_type(margs[5],"timestamp",float(margs[6]))
				cll.stream.set_type(margs[5],"payload",margs[7])
			return (mtype, cll)
		else:
			if debug > 0 : print  str + " is not implemented accepted messages are: " + str(self.types)
